package com.photoeditor.demo.model.store.module;

import com.common.base.ComponentContext;
import com.photoeditor.demo.statistics.StatisticsConstant;
import com.photoeditor.demo.util.AndroidDevice;
import com.photoeditor.demo.util.RegionUtil;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;


/**

 *
 * 这个用于执行一些网络请求
 */
public class StoreNetUtil {
    private static StoreNetUtil mInstance;
    private ExecutorService mPoolService;

    private ThreadFactory mThreadFactory;

    //处理成功
    public static final int RESULT_OK = 1;

    //服务器处理异常
    public static final int RESULT_FAILED = -1;

    //业务异常,见errorcode列表
    public static final int RESULT_ERROR = -2;

    private StoreNetUtil(){
        mThreadFactory = new ThreadFactory() {

            private final AtomicInteger mCount = new AtomicInteger(1);

            public Thread newThread(Runnable r) {
                return new Thread(r, "StoreNetUtil Runnable #" + mCount.getAndIncrement());
            }
        };
        mPoolService = Executors.newCachedThreadPool(mThreadFactory);
    }

    public synchronized static StoreNetUtil getInstance(){
        if(mInstance == null){
            mInstance = new StoreNetUtil();
        }
        return mInstance;
    }

    public void destory() {
        try {
            mPoolService.shutdownNow();
        } catch (Throwable e) {
        }
    }



    public void requestNetworkData(final String urlStr, final IRequestListener listener) {
        com.common.statistics.StatisticsUtils.statisics(StatisticsConstant.UMENG_CUSTOM_EVENT_SERVER_DATA_REQUEST,
                "",
                "url", urlStr);
        if (!AndroidDevice.isNetworkOK(ComponentContext.getContext())) {
            if(listener != null) {
                listener.onRequestFailure();
            }
            return;
        }
        mPoolService.submit(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection conn = null;
                try {
                    long startTime = System.currentTimeMillis();
                    URL url = new URL(urlStr);
                    conn = (HttpURLConnection) url.openConnection();
                    conn.setConnectTimeout(30 * 1000);
                    conn.setReadTimeout(30 * 1000);
                    conn.setRequestMethod("GET");
                    int webFileLength = conn.getContentLength();
                    InputStream inStream = conn.getInputStream();
                    long connectLatency = System.currentTimeMillis() - startTime;
                    if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
                        byte[] buffer = new byte[1024];
                        int len = 0;
                        while ((len = inStream.read(buffer)) != -1) {
                            outStream.write(buffer, 0, len);
                        }
                        if(listener != null) {
                            listener.onRequestFinish(outStream.toString());
                        }
                        outStream.close();
                        statistics(true, startTime, webFileLength, connectLatency, urlStr, null);
                    } else {
                        if(listener != null) {
                            listener.onRequestFailure();
                        }
                        statistics(false, 0, 0, 0, urlStr,
                                new Exception(String.valueOf(conn.getResponseCode())));
                    }
                    inStream.close();
                } catch (Throwable e) {
                    e.printStackTrace();
                    if(listener != null) {
                        listener.onRequestFailure();
                    }
                    statistics(false, 0, 0, 0, urlStr, e);
                } finally {
                    if(conn != null) {
                        conn.disconnect();
                    }
                }
            }
        });
    }

    private void statistics(boolean success, long startTime, long downloadedFileLength, long connectLatency, String downloadUrl, Throwable e) {
        long downloadDuration = System.currentTimeMillis() - startTime;
        float downloadSpeed = (float) (downloadedFileLength * 1.0 / 1024 / (downloadDuration * 1.0 / 1000));
        String event = success ?
                StatisticsConstant.UMENG_CUSTOM_EVENT_SERVER_DATA_REQUEST_SUCCESS :
                StatisticsConstant.UMENG_CUSTOM_EVENT_SERVER_DATA_REQUEST_ERROR;
        String country = RegionUtil.getSimCountry();
        String model = android.os.Build.BRAND + ":" + android.os.Build.MODEL;
        if (success) {
            com.common.statistics.StatisticsUtils.statisics(event,
                    "",
                    (int) downloadSpeed,
                    "speed", String.valueOf((int) downloadSpeed / 10),
                    "country", country,
                    "model", model,
                    "connectLatency", String.valueOf(connectLatency / 10),
                    "network", AndroidDevice.getNetworkTypeName(),
                    "url", StoreOnlineBean.removeQueryString(downloadUrl));
        } else {
            com.common.statistics.StatisticsUtils.statisics(event,
                    "",
                    0,
                    "error-msg", e.getMessage(),
                    "country", country,
                    "model", model,
                    "network", AndroidDevice.getNetworkTypeName(),
                    "url", StoreOnlineBean.removeQueryString(downloadUrl));
        }
    }

    public interface IRequestListener {
        void onRequestFinish(String text);
        void onRequestFailure();
    }



}
